<template>
  <div style="display: flex; width: 100%; padding: 10px" v-if="isUserCode">
    <div
      ref="chartRef"
      style="width: 50%; height: 300px"
      class="echarts1"
    ></div>
    <div
      ref="chartRe1"
      style="width: 50%; height: 300px"
      class="echarts2"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartVisible: Object,
  weight: Number,
});
// 定义响应式数据
const chartRef = ref(null);
const chartRe1 = ref(null);
let chartInstance: any = null;
let chartInstance1: any = null;
const isUserCode = ref(true);
const emits = defineEmits(['changeVisible']);
// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);

    const option = {
      title: [{ text: '单次剂量', left: 'center' }],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: [
        {
          type: 'category',
          data: ['最小', '单次', '最大'],
          axisLabel: {
            interval: 0,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          interval: 1,
          axisLabel: {
            formatter: '{value}' + props.chartVisible?.minPackUnitText,
          },
        },
      ],
      series: [
        {
          name: '单次剂量',
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: function (params: { dataIndex: any }) {
              let colorList = ['#99CCFF', '#00CCFF', '#6666FF'];
              return colorList[params.dataIndex];
            },
          },
        },
      ],
    };
    chartInstance.setOption(option);
  }
};
const initChart1 = () => {
  if (chartRe1.value) {
    chartInstance1 = echarts.init(chartRe1.value);

    const option = {
      title: [{ text: '单日剂量', left: 'center' }],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: [
        {
          type: 'category',
          data: ['最大'],
          axisLabel: {
            interval: 0,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          interval: 1,
          axisLabel: {
            formatter: '{value}' + props.chartVisible?.minPackUnitText,
          },
        },
      ],
      series: [
        {
          name: '单日剂量',
          type: 'bar',
          barWidth: '20%',
          itemStyle: {
            color: '#6666FF',
          },
        },
      ],
    };

    chartInstance1.setOption(option);
  }
};
/**
 * 计算最优的y轴间隔（支持小数）
 * @param maxValue 最大值
 * @returns 合适的间隔值
 */
function calculateOptimalInterval(maxValue: number): number {
  if (maxValue <= 0) return 1;

  // 根据最大值范围确定间隔
  if (maxValue < 1) {
    // 很小的小数值，使用0.1或0.2间隔
    return maxValue < 0.2 ? 0.05 : 0.1;
  } else if (maxValue < 10) {
    // 中等范围值，使用0.5或1间隔
    return maxValue < 5 ? 0.5 : 1;
  } else {
    // 较大值，使用整数间隔
    const magnitude = Math.pow(10, Math.floor(Math.log10(maxValue)));
    const normalized = maxValue / magnitude;

    if (normalized < 2) return magnitude * 0.2;
    if (normalized < 5) return magnitude * 0.5;
    return magnitude * 1;
  }
}
// 更新图表数据
const updateChartData = () => {
  const usageList = props.chartVisible?.usageList.find(
    (item: any) => item.usageCode === props.chartVisible?.usageCode
  );
  if (!usageList) {
    isUserCode.value = false;
    return;
  }
  // const singleMin = (props?.weight * usageList.singleMin) / 50
  const singleMin = (((props.weight ?? 50) * usageList.singleMin) / 50).toFixed(
    2
  );
  const singleMax = (((props.weight ?? 50) * usageList.singleMax) / 50).toFixed(
    2
  );
  const dailyMax = (((props.weight ?? 50) * usageList.dailyMax) / 50).toFixed(
    2
  );

  const average = ((Number(singleMin) + Number(singleMax)) / 2).toFixed(2);
  console.log(singleMin, singleMax, dailyMax, average);

  if (chartInstance && props.chartVisible) {
    // 根据tableData更新第一个图表的数据
    const chartData = [singleMin, average, singleMax];

    // 计算最大值并确定合适的间隔（支持小数）
    // const maxDataValue = Math.max(...chartData);
    const chartData1 = [Number(dailyMax)];
    const maxDataValue = Math.max(...chartData1);
    // 动态计算间隔：根据最大值范围确定合适的间隔
    const yAxisInterval = calculateOptimalInterval(maxDataValue);

    const option = {
      yAxis: [
        {
          type: 'value',
          interval: yAxisInterval,
          min: 0,
          max:
            maxDataValue > 0 ? maxDataValue + yAxisInterval : yAxisInterval * 5,
          axisLabel: {
            // 支持小数显示，保留2位小数
            formatter: (value: any) => {
              // 如果值是整数，显示整数；否则显示2位小数
              return Number.isInteger(value)
                ? `${value}${props.chartVisible?.minPackUnitText || ''}`
                : `${value.toFixed(2)}${
                    props.chartVisible?.minPackUnitText || ''
                  }`;
            },
          },
        },
      ],
      series: [
        {
          data: chartData,
          // 确保系列数据格式正确
          type: 'bar', // 或其他图表类型
          itemStyle: {
            extraCssText: 'svg-element-class',
          },
        },
      ],
      // 确保提示框显示小数
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const value = params[0];

          return `${value.seriesName}: ${value.value}${
            props.chartVisible?.minPackUnitText || ''
          }`;
        },
      },
    };

    chartInstance.setOption(option);
    chartInstance.on('click', function (params: any) {
      if (params.componentType === 'series' && params.seriesType === 'bar') {
        // console.log('点击数据详情:', {
        //   系列名称: params.seriesName,
        //   数据索引: params.dataIndex,
        //   数据值: params.value,
        //   完整数据项: params.data,
        //   坐标系信息: params.coord,
        // });
        emits('changeVisible', {
          ...props.chartVisible,
          dataIndex: params.dataIndex,
          value: params.value,
        });
      }
    });
  }

  if (chartInstance1 && props.chartVisible) {
    // 根据tableData更新第二个图表的数据
    const chartData = [dailyMax];
    const chartData1 = [Number(dailyMax)];
    const maxDataValue = Math.max(...chartData1);
    const yAxisInterval = maxDataValue > 0 ? Math.ceil(maxDataValue / 5) : 1;

    const option = {
      yAxis: [
        {
          type: 'value',
          interval: yAxisInterval,
          min: 0,
          max: maxDataValue > 0 ? maxDataValue + yAxisInterval : 5,
          axisLabel: {
            formatter: '{value}' + props.chartVisible?.minPackUnitText,
          },
        },
      ],
      series: [
        {
          data: chartData,
        },
      ],
    };
    chartInstance1.setOption(option);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
    chartInstance1.resize();
  }
};

// 监听tableData变化
watch(
  () => props.chartVisible,
  () => {
    // 每次数据变化时都尝试初始化图表（内部有检查）
    nextTick(() => {
      initChart();
      initChart1();
      // 确保添加事件监听器只执行一次
      if (chartInstance && chartInstance1) {
        window.addEventListener('resize', handleResize);
      }
      updateChartData();
    });
  },
  { deep: true, immediate: true }
);
watch(
  () => props.weight,
  () => {
    updateChartData();
  },
  { deep: true, immediate: true }
);
// 生命周期钩子
onMounted(() => {
  // 组件挂载后初始化图表
  // initChart();
  // initChart1();
  // window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance1.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
/* ... existing code ... */
</style>
